package priv.yiyuan.example.composite.ticket;

import java.util.ArrayList;
import java.util.List;

/**
 * 复合工单
 * <p>
 * 组合模式-组合节点
 *
 * @author YiYuan
 * @data 2025/8/29
 * @apoNote
 */
public class CompositeTicket extends TicketComponent {

    private List<TicketComponent> children = new ArrayList<>();

    public CompositeTicket(String ticketId, String description) {
        super(ticketId, description);
    }

    @Override
    public void add(TicketComponent component) {
        children.add(component);
        component.setParent(this);
    }

    @Override
    public void remove(TicketComponent component) {
        children.remove(component);
        component.setParent(null);
    }

    @Override
    public void process(TicketHandler handler) {

        System.out.println("\n开始处理复合工单: " + description + " (ID: " + ticketId + ")");
        for (TicketComponent child : children) {

            if (!child.isCompleted()) {
                child.process(handler);
            }
        }

        if (checkChildrenCompletion()) {
            this.updateStatus(TicketStatus.COMPLETED);
            System.out.println("复合工单 " + ticketId + " 所有子工单已完成");
        }
        else {
            this.updateStatus(TicketStatus.IN_PROGRESS);
        }

    }

    private boolean checkChildrenCompletion() {
        for (TicketComponent child : children) {

            if (!child.isCompleted()) {
                return false;
            }

        }

        return true;
    }

    @Override
    public boolean isCompleted() {
        return status == TicketStatus.COMPLETED;
    }

    @Override
    public void display(String indent) {
        System.out.println(indent + " [复合工单] " + ticketId + ": " + description + " (" + status + ")");
        for (TicketComponent child : children) {
            child.display("   ");
        }
    }
}
